package com.xiaxiang.xiawan.Effect.Adapter;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mk on 2017/8/4.
 */

public class EffectPagerAdapter extends PagerAdapter {
    private final String TAG = "EffectPagerAdapter";
    private List<View> viewList = new ArrayList<View>();
    private String[] tabText;

    public EffectPagerAdapter(List<View> viewList, String[] tabText) {
        this.viewList = viewList;
        this.tabText = tabText;
    }

    @Override
    public int getCount() {
        return viewList.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager)container).removeView((View)object);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        //这里前面加的空格就是为图片显示
        SpannableString sp = new SpannableString("  "+ tabText[position]);
        return sp;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        Log.i(TAG, "instantiateItem : " + position);
        // 当存在父view时，子view要与父view解绑
        try {
            if( viewList.get(position).getParent() == null)
                ((ViewPager)container).addView(viewList.get(position), 0);
            else{
                ((ViewGroup)viewList.get(position).getParent()).removeView(viewList.get(position) );
                ((ViewPager)container).addView(viewList.get(position), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return viewList.get(position);
    }
}
